﻿using UnityEngine;

namespace Assets.Backpack.Scripts.Player
{
    /// <summary>
    /// 控制玩家移动脚本
    /// </summary>
    public class PlayerMovement : MonoBehaviour
    {
        private Rigidbody2D rb;
        private Collider2D coll;
        private Animator anim;
        /// <summary>
        /// 速度
        /// </summary>
        [SerializeField] private float speed;
        /// <summary>
        /// 移动方向
        /// </summary>
        private Vector2 movement;
        /// <summary>
        /// 背包
        /// </summary>
        [SerializeField] private GameObject myBag;
        /// <summary>
        /// 背包是否打开
        /// </summary>
        private bool isOpen;

        private void Awake()
        {
            rb = GetComponent<Rigidbody2D>();
            coll = GetComponent<Collider2D>();
            anim = GetComponent<Animator>();
        }

        private void Update()
        {
            Movement();
            SwitchAnim();
            
            
            if (Input.GetKeyDown(KeyCode.B))
            {
                //TODO:放到UIController里面管理显示打开
                isOpen = !isOpen;
                myBag.SetActive(isOpen);
            }
        }

        /// <summary>
        /// 移动
        /// </summary>
        void Movement()
        {
            movement.x = Input.GetAxisRaw("Horizontal");
            movement.y = Input.GetAxisRaw("Vertical");
            rb.MovePosition(rb.position + movement * speed * Time.deltaTime);

        }

        /// <summary>
        /// 切换动画
        /// </summary>
        void SwitchAnim()
        {
            //保证Horizontal归0时，保留movment的值来切换idle动画的blend tree
            if (movement != Vector2.zero)
            {
                anim.SetFloat("horizontal", movement.x);
                anim.SetFloat("vertical", movement.y);
            }
            anim.SetFloat("speed", movement.magnitude);
        }
    }
}
